package name.williamwall.buxoid;

/**
 * This software is made available under the GNU General Public License v3
 * and has absolutely no warranty. You may change the software to suit your needs.
 * 
 * Author: William Wall, IV
 * 
 * AccountAdapter is used to adjust the balance of an account and format it with a 
 * currency format.
 */

import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import android.content.Context;
import android.database.Cursor;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class AccountAdapter extends SimpleCursorAdapter {
	private static NumberFormat moneyFormat = NumberFormat.getCurrencyInstance();
	private static SimpleDateFormat mWriteFormat = new SimpleDateFormat("yyyy-MM-dd k:mm a");
	private static SimpleDateFormat mReadFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
	private int mBalanceType;
	
	public AccountAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int balanceType) {
		super(context, layout, c, from, to);
		mBalanceType = balanceType;
		moneyFormat.setCurrency(Buxoid.mDb.getCurrency());
	}

	@Override
	public void setViewText(TextView v, String text) {
		int id = v.getId();
		if (id == R.id.row_account_balance) {
			double balance = Double.parseDouble(text);
			if (mBalanceType > 0) {
				Cursor c = super.getCursor();
				// include pending transactions in balance
				balance += Buxoid.mDb.getPendingBalance(c.getString(c.getColumnIndexOrThrow(BuxoidDb.ACCOUNT_BUXID)));
			}

			v.setText(moneyFormat.format(balance));
		} else if (id == R.id.row_account_sync) {
			try {
				v.setText("Last synced: " + mWriteFormat.format(mReadFormat.parse(text)));
			} catch (ParseException e) {
			}
		} else {
			super.setViewText(v, text);
		}
	}
}
